package dao

import (
	"context"
	"gorm.io/gorm"
	"time"
)

type CommentDao interface {
	Insert(ctx context.Context, u Comment) error
	// FindByBiz 只查找一级评论
	FindByBiz(ctx context.Context, biz string, bizId, minID, limit int64) ([]Comment, error)
	// Delete 删除本节点和其对应的子节点
	Delete(ctx context.Context, u Comment) error
	GetCommentByIds(ctx context.Context, ids []int64) ([]Comment, error)
	FindRepliesByPid(ctx context.Context, pid int64, offset, limit int) ([]Comment, error)
	FindRepliesByRid(ctx context.Context, rid int64, maxId, limit int) ([]Comment, error)
}
type CommentGormDao struct {
	db *gorm.DB
}

func NewAccountGormDao(db *gorm.DB) CommentDao {
	return &CommentGormDao{db: db}
}
func (c *CommentGormDao) GetCommentByIds(ctx context.Context, ids []int64) ([]Comment, error) {
	var res []Comment
	err := c.db.WithContext(ctx).Where("id in ?", ids).Find(&res).Error
	return res, err
}
func (c *CommentGormDao) FindRepliesByRid(ctx context.Context, rid int64, maxId,
	limit int) ([]Comment, error) {
	var res []Comment
	err := c.db.WithContext(ctx).Where("rid=? and id>?", rid, maxId).
		Limit(limit).Find(&res).Error
	return res, err
}
func (c *CommentGormDao) FindRepliesByPid(ctx context.Context, pid int64, offset,
	limit int) ([]Comment, error) {
	var res []Comment
	err := c.db.WithContext(ctx).Where("pid=?", pid).Offset(offset).Limit(limit).Find(&res).Error
	return res, err
}
func (c *CommentGormDao) Insert(ctx context.Context, u Comment) error {
	now := time.Now().UnixMilli()
	u.Ctime = now
	return c.db.
		WithContext(ctx).
		Create(&u).
		Error
}

// FindByBiz 只查找一级评论
func (c *CommentGormDao) FindByBiz(ctx context.Context, biz string, bizId, minID,
	limit int64) ([]Comment, error) {
	var res []Comment
	err := c.db.WithContext(ctx).Where("biz=? and biz_id=? and id<? and pid is null",
		biz, bizId, minID).Limit(int(limit)).Find(&res).Error
	return res, err
}

// Delete 删除本节点和其对应的子节点
func (c *CommentGormDao) Delete(ctx context.Context, u Comment) error {
	return c.db.WithContext(ctx).Delete(&Comment{
		Id: u.Id,
	}).Error
}
